package org.example.rzfx.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.rzfx.dto.Result;
import org.example.rzfx.entity.AlarmRule;
import org.example.rzfx.mapper.AlarmRuleMapper;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 告警规则控制器
 */
@RestController
@RequestMapping("/api/alarm-rule")
@CrossOrigin
public class AlarmRuleController {
    
    @Resource
    private AlarmRuleMapper alarmRuleMapper;
    
    /**
     * 查询所有告警规则
     */
    @GetMapping("/list")
    public Result<?> listRules() {
        return Result.success(alarmRuleMapper.selectList(null));
    }
    
    /**
     * 分页查询告警规则
     */
    @GetMapping("/page")
    public Result<?> pageRules(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "20") Integer pageSize) {
        Page<AlarmRule> page = new Page<>(pageNum, pageSize);
        return Result.success(alarmRuleMapper.selectPage(page, null));
    }
    
    /**
     * 获取告警规则详情
     */
    @GetMapping("/{id}")
    public Result<AlarmRule> getRuleDetail(@PathVariable Long id) {
        AlarmRule rule = alarmRuleMapper.selectById(id);
        if (rule == null) {
            return Result.error("告警规则不存在");
        }
        return Result.success(rule);
    }
    
    /**
     * 创建告警规则（管理员权限）
     */
    @PostMapping("/create")
    @SaCheckRole("1")
    public Result<Void> createRule(@Valid @RequestBody AlarmRule rule) {
        alarmRuleMapper.insert(rule);
        return Result.success("创建成功", null);
    }
    
    /**
     * 更新告警规则（管理员权限）
     */
    @PutMapping("/update")
    @SaCheckRole("1")
    public Result<Void> updateRule(@Valid @RequestBody AlarmRule rule) {
        if (alarmRuleMapper.selectById(rule.getId()) == null) {
            return Result.error("告警规则不存在");
        }
        alarmRuleMapper.updateById(rule);
        return Result.success("更新成功", null);
    }
    
    /**
     * 删除告警规则（管理员权限）
     */
    @DeleteMapping("/{id}")
    @SaCheckRole("1")
    public Result<Void> deleteRule(@PathVariable Long id) {
        alarmRuleMapper.deleteById(id);
        return Result.success("删除成功", null);
    }
    
    /**
     * 启用/禁用告警规则（管理员权限）
     */
    @PutMapping("/status/{id}/{enabled}")
    @SaCheckRole("1")
    public Result<Void> updateStatus(@PathVariable Long id, @PathVariable Integer enabled) {
        AlarmRule rule = alarmRuleMapper.selectById(id);
        if (rule == null) {
            return Result.error("告警规则不存在");
        }
        rule.setEnabled(enabled);
        alarmRuleMapper.updateById(rule);
        return Result.success("更新成功", null);
    }
}

